﻿using Microsoft.AspNetCore.Mvc;
using ERP.ERPSystem.WarehouseManagement;
using ERP.ERPSystem.WarehouseManagement.Dto;
using System.Threading.Tasks;
using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Text.Json;

namespace ERP.Web.Controllers.WarehouseManagement
{
    /// <summary>
    /// 仓储管理-赋码管理控制器
    /// </summary>
    public class CodingManagementController : Controller
    {
        private readonly ICodingManagementService _codingManagementService;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ILogger<CodingManagementController> _logger;

        public CodingManagementController(
            ICodingManagementService codingManagementService,
            IWebHostEnvironment webHostEnvironment,
            ILogger<CodingManagementController> logger)
        {
            _codingManagementService = codingManagementService;
            _webHostEnvironment = webHostEnvironment;
            _logger = logger;
        }

        public IActionResult CodingManagementQuery()
        {
            return View();
        }

        public IActionResult MaterialProductSelect()
        {
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> GetMaterialProductList(string materialCode, string materialName, int page = 1, int limit = 10)
        {
            var result = await _codingManagementService.GetMaterialProductPagedListAsync(
                materialCode,
                materialName,
                (page - 1) * limit,
                limit
            );

            return Json(new
            {
                code = 0,
                msg = "",
                count = result.TotalCount,
                data = result.Items
            });
        }

        [HttpGet]
        public async Task<IActionResult> GetPagedList(string codeType, string businessCode, string businessName, int page = 1, int limit = 10)
        {
            try
            {
                var result = await _codingManagementService.GetPagedListAsync(
                    codeType, 
                    businessCode, 
                    businessName, 
                    (page - 1) * limit, 
                    limit
                );

                // 确保URL路径正确
                var items = result.Items.Select(item => new
                {
                    item.Id,
                    item.BarTypes,
                    item.BarFormat,
                    item.BarContext,
                    item.BusinessCode,
                    item.BusinessName,
                    item.BarCode,
                    item.IsNo,
                    // 确保URL以/开头
                    Url = !string.IsNullOrEmpty(item.Url) ? (item.Url.StartsWith("/") ? item.Url : "/" + item.Url) : null
                });

                _logger.LogInformation($"返回条码列表数据: {JsonSerializer.Serialize(items)}");

                return Json(new { 
                    code = 0, 
                    msg = "", 
                    count = result.TotalCount, 
                    data = items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError($"获取编码列表失败: {ex.Message}");
                return Json(new { code = 1, msg = "获取数据失败", count = 0, data = new object[] { } });
            }
        }

        [HttpPost]
        public async Task<IActionResult> SaveBarcodeImage([FromBody] SaveBarcodeImageInput input)
        {
            try
            {
                if (string.IsNullOrEmpty(input.ImageData))
                {
                    _logger.LogWarning("图片数据为空");
                    return Json(new { success = false, message = "图片数据不能为空" });
                }

                // 创建保存目录
                var uploadPath = Path.Combine(_webHostEnvironment.WebRootPath, "images", "CodeIng");
                _logger.LogInformation($"上传目录: {uploadPath}");
                
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                try
                {
                    // 处理Base64图片数据
                    var base64Data = input.ImageData.Contains(",") ? 
                        input.ImageData.Split(',').Last() : 
                        input.ImageData;

                    var imageBytes = Convert.FromBase64String(base64Data);

                    // 生成文件名
                    var fileName = $"barcode_{DateTime.Now:yyyyMMddHHmmss}_{Guid.NewGuid():N}.png";
                    var filePath = Path.Combine(uploadPath, fileName);
                    _logger.LogInformation($"保存文件: {filePath}");

                    // 保存为PNG文件
                    await System.IO.File.WriteAllBytesAsync(filePath, imageBytes);

                    // 验证文件是否成功保存
                    if (!System.IO.File.Exists(filePath))
                    {
                        _logger.LogError("文件保存失败");
                        return Json(new { success = false, message = "文件保存失败" });
                    }

                    // 返回相对路径
                    var relativePath = $"/images/CodeIng/{fileName}";
                    _logger.LogInformation($"文件保存成功，返回路径: {relativePath}");

                    return Json(new { success = true, url = relativePath });
                }
                catch (Exception ex)
                {
                    _logger.LogError($"保存图片文件失败: {ex.Message}");
                    return Json(new { success = false, message = $"保存图片文件失败: {ex.Message}" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"保存条码图片失败: {ex.Message}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        [HttpPost]
        public async Task<IActionResult> Create([FromBody] CodingManagementDTO input)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _codingManagementService.CreateAsync(input);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError($"创建编码失败: {ex.Message}");
                return StatusCode(500, new { message = "创建编码失败，请检查日志了解详细信息。" });
            }
        }

        [HttpGet]
        public async Task<IActionResult> GenerateBarcode(string barFormat)
        {
            var barcode = await _codingManagementService.GenerateBarcodeAsync(barFormat);
            return Json(new { success = true, data = barcode });
        }

        /// <summary>
        /// 删除编码
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _codingManagementService.DeleteAsync(id);
                return Json(new { success = true, message = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError($"删除编码失败: {ex.Message}");
                return Json(new { success = false, message = "删除失败" });
            }
        }
    }

    public class SaveBarcodeImageInput
    {
        public string ImageData { get; set; }
    }
}
